<template>
  <div>
    <el-dialog
      :title="!deptForm.id ? '新增部门' : '编辑部门'"
       :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      width="520px">
      <el-form ref="deptForm" :model="deptForm" label-width="80px">
        <el-form-item label="部门名称" prop="deptName"
        :rules="[{ required: true, message: '请输入部门名称', trigger: 'blur' }]">
          <el-input v-model="deptForm.deptName" placeholder="请输入部门名称" :disabled="!canAddOrEditDeptment"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <div><el-button @click="delDept" size="mini" type="danger" v-if="canDel && isAuth('recruitment:hrrecruitmentdept:delete')">删除</el-button></div>
        <div>
          <el-button @click="dialogVisible = false" size="mini">取消</el-button>
          <el-button type="primary" @click="submitDeptForm('deptForm')" size="mini" v-if="canAddOrEditDeptment">确定</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import formUtil from '@/utils/formUtil'
export default {
  data () {
    return {
      dialogVisible: false,
      deptForm: {
        deptName: '',
        deptPid: '',
      },
      canDel: false,
    };
  },
  components: {},
  computed: {
    canAddOrEditDeptment() {
      return (this.isAuth('recruitment:hrrecruitmentdept:save') && !this.deptForm.id) || (this.isAuth('recruitment:hrrecruitmentdept:update') && this.deptForm.id)
    }
  },
  methods: {
    async init(dept) {
      formUtil.resetData(this.deptForm);
      this.canDel = dept && !dept.children ? true : false;
      if(this.$refs.deptForm) this.$refs.deptForm.clearValidate();
      if(dept) {
        let data = await this.$httpN.postB('recruitment/hrrecruitmentdept/info', {id: dept.id})
        this.deptForm = data
      }
      this.dialogVisible = true;
    },
    submitDeptForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.deptForm.deptPid = '1'
          if(!await this.$httpN.postB(!this.deptForm.id ? "recruitment/hrrecruitmentdept/save" : "recruitment/hrrecruitmentdept/update", this.deptForm)) return;
          formUtil.submitSuccess('保存成功');
          this.dialogVisible = false;
          this.reload();
        }
      });
    },
    delDept() {
      formUtil.submitConfirm('请问您是否确认删除该部门', async ()=> {
        if(!await this.$httpN.postB('recruitment/hrrecruitmentdept/delete', [this.deptForm.id], false)) return;
        formUtil.submitSuccess('删除成功');
        this.dialogVisible = false;
        this.reload();
      })
    },
    reload() {
      this.$emit("refresh");
    }
  }
}
</script>

<style lang='scss' scoped>
.el-dialog {
  .el-form {
    max-height: 500px;
    overflow: auto;
  }
  .dialog-footer {
    display: flex;
    justify-content: space-between;
  }
}
.el-select-dropdown__item {
  padding: 0;
}
.el-select-dropdown__item.hover, .el-select-dropdown__item:hover {
  background-color: #FFF;
}
</style>